import md5 from 'js-md5';

import { Login } from '@/api/user.js';
import { getCookie, setCookie, removeCookie } from '../../utils/support';


const user = {
    state: {
        name: getCookie('name') || "",
        roleid: getCookie('roleid') || ""
    },
    mutations: {

        SET_NAME: (state, name) => {
            state.name = name;
        },

        SET_ROLEID: (state, roleid) => {
            state.roleid = roleid;
        }
    },
    actions: {

        LOGIN_AC: ({ commit }, userInfo) => {
            return new Promise((resolve) => {
                console.log(commit);

                const { username, password } = userInfo;
                console.log(username);

                console.log(md5(password + md5(password).substr(10, 10) + 2014));
                userInfo.password = md5(password + md5(password).substr(10, 10) + 2014);

                Login(userInfo).then(res => {
                    console.log(res);

                    setCookie("token", res["token"], 1);
                    setCookie("name", res["name"], 1);
                    setCookie("roleid", res["roleid"], 1);
                    setCookie("username", res["username"], 1);


                    commit("SET_NAME", res['name']);
                    commit("SET_ROLEID", res['roleid']);

                    resolve(res);
                })

            })
        },
        LOGOUT_AC: ({ commit }) => {

            commit("SET_NAME", "");
            commit("SET_ROLEID", "");


            removeCookie("token");
            removeCookie("name");
            removeCookie("roleid");
            removeCookie("username");
        }
    }
}
export default user;